<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\Detail;
use App\Admin\Actions\Grid\User\Account;
use App\Admin\Actions\Grid\User\Deduction;
use App\Admin\Actions\Grid\User\Recharge;
use App\Admin\Actions\Grid\User\ResetPassword;
use App\Admin\Repositories\User;
use App\Models\Configuration;
use App\Models\Hierarchy;
use App\Models\User as Model;
use Carbon\Carbon;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Support\Facades\Redis;

class UserController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new User(), function (Grid $grid) {

            $grid->model()->with('hierarchy');
            if(Admin::user()->isRole('agent')){
                $grid->model()->where('agent_id','=',Admin::user()->id);
            }
            $grid->model()->orderByDesc('id');


            $grid->column('id');
            if(Admin::user()->isRole('administrator')) {
                //$grid->column('agent.name', trans('user.fields.agent_name'));
            }
            $grid->column('parent_id')->display(function($var){
                if($var != 0){
                    $str = "<a href='/admin/users?id=$var' target='_blank'>$var</a>";
                    return $str;
                }else{
                    return $var;
                }
            });
            //$grid->column('tiktokid');
            $grid->column('tiktokno_str','账号')->display(function (){
                $str = $this->tiktokno;
                if($this->hierarchy_id != 1){
                    $str .= "({$this->hierarchy->title})";
                }
                return $str;
            });

            $now_t = Carbon::now()->timestamp;
            $grid->column('online')->display(function ($var)use($now_t){
                $t = Redis::ZSCORE('userauthlist',$this->id);
                if(!empty($t)){
                    if($now_t - $t < 5 *60){
                        return '<i class="fa fa-circle" style="font-size: 13px;color: #28a745"></i>&nbsp;&nbsp;';
                    }
                }
                return '<i class="fa fa-circle" style="font-size: 13px;color: #6c757d"></i>&nbsp;&nbsp;';
            });
            $grid->column('shopname');
            //$grid->column('tiktokno');
            $grid->column('shopstar');
            $grid->column('shopcredit')->copyable();
            $grid->column('state')->display(function ($var){
                return Model::STATES[$var];
            });

            $grid->column('balance')->display(function ($var) {
                return $var / 100;
            });

            $grid->column('recharge','充值总额')->display(function ($var) {
                $w = \App\Models\Account::query()->whereIn('type',[1,2] )->where('user_id','=',$this->id)->sum('amount');
                return $w / 100;
            });



            //$grid->column('lang');
            $grid->column('link','店铺链接')->modal("店铺链接",function ($model){
                $data = $model->row;
                return view("Admin.copylink",compact('data'));
            });
            /*
            ->display(function (){
                $link = Configuration::getItem("links_shopCenter");
                return $link;
            })->copyable()->width("50px");
            */
            $grid->column('remark');
            $grid->column('login_time_last');

            $grid->quickSearch('id','nickname','tiktokno','tiktokid');
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('parent_id');
                $filter->equal('tiktokid');
                $filter->equal('tiktokno');
                $filter->equal('shopname');
                $filter->equal('state')->select(Model::STATES);
                $filter->equal('lang');
                $filter->equal('remark');
                $filter->where('ip', function ($query) {
                    $query->where('ip_last', 'like', "%{$this->input}%")
                        ->orWhere('ip_register', 'like', "%{$this->input}%");
                });
            });

            $grid->showQuickEditButton();
            $grid->disableViewButton();
            $grid->disableCreateButton();
            $grid->disableDeleteButton();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new Detail());
                if(Admin::user()->isRole('administrator')){
                    $actions->append(new Recharge());
                    $actions->append(new Deduction());
                }
                $actions->append(new Account());
                $actions->append(new ResetPassword());
            });



        });
    }


    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    public function detail($id)
    {
        return Show::make($id, new User(), function (Show $show) {
            $show->disableListButton();
            $show->field('id');
            $show->field('tiktokno');
            $show->field('shopname');
            $show->field('balance');
            $show->field('state')->as(function ($var){
                return Model::STATES[$var];
            });
            $show->field('denial_reason');
            $show->avatar()->image();
            $show->field('lang');
            $show->field('remark');


            $show->field('shoptype')->as(function ($var){
                return Model::SHOPTAYES[$var];
            });
            $show->field('shopdesc');
            $show->field('shopstar');
            $show->field('shopcredit');

            $show->field('created_at');

            $show->html(function () {
                $num = Model::query()->where('id','<>',$this->id)->where(function ($q){
                    $q->where('ip_last','=',$this->ip_last)->orWhere('ip_register','=',$this->ip_last);
                })->count();
                $str = '<div class="show-field form-group row">
                            <div class="col-sm-2 control-label">
                                   <span>'.trans('user.fields.ip_last').'</span>
                            </div>
                            <div class="col-sm-8">
                                <div class="box box-solid box-default no-margin box-show">
                                    <div class="box-body">'.$this->ip_last.'</div>
                                </div>
                            </div>
                            <div class="col-sm-2  control-label" style="text-align: left"><span><a href="'.admin_url('users').'?ip='.$this->ip_last.'" target="_blank">【'.$num.'】</a></span></div>
                        </div>';
                return $str;
            });

            $show->html(function () {
                $num = Model::query()->where('id','<>',$this->id)->where(function ($q){
                    $q->where('ip_last','=',$this->ip_register)->orWhere('ip_register','=',$this->ip_register);
                })->count();
                $str = '<div class="show-field form-group row">
                                <div class="col-sm-2 control-label">
                                       <span>'.trans('user.fields.ip_register').'</span>
                                </div>
                                <div class="col-sm-8">
                                    <div class="box box-solid box-default no-margin box-show">
                                        <div class="box-body">'.$this->ip_register.'</div>
                                    </div>
                                </div>
                                <div class="col-sm-2  control-label" style="text-align: left"><span><a href="'.admin_url('users').'?ip='.$this->ip_register.'" target="_blank">【'.$num.'】</a></span></div>
                            </div>';
                return $str;
            });
            $show->field('login_time_last');

        });
    }



    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new User(), function (Form $form) {

            // $form->text('tiktokid');
            $form->text('tiktokno');
            //$form->text('nickname');
            $form->text('shopname');
            $form->switch('withdrawal_switch');
            //$form->text('state');
            $form->select('hierarchy_id', '层级')->options($this->hierarchy())->default(1);
            $form->select('state')->options(Model::STATES)->required();
            $form->text('denial_reason');
            $form->image('avatar')->uniqueName()->removable(false)->autoUpload()->disk ('oss')->saveFullUrl()->retainable ();
            //->disk ('oss')->saveFullUrl()->retainable ()->removable (false);

            $form->text('lang');
            //$form->text('timezone');
            $form->text('remark');


            $form->select('shoptype')->options(Model::SHOPTAYES);
            $form->text('shopdesc');
            $form->text('shopstar');
            $form->text('shopcredit');



            $form->multipleImage('identity')->uniqueName()->retainable()->saving(function ($paths) {
                // 可以转化为由 , 隔开的字符串格式
                return implode(',', $paths);
            });

        });
    }


    public function hierarchy(): array
    {
        $hierarchies = Hierarchy::all()->toArray();
        $data = [];
        foreach ($hierarchies as $k => $v) {
            $data[$v['id']] = $v['title'];
        }
        return $data;
    }

}
